//
// Created by 17775 on 2024/12/20.
//

#ifndef RAYCI_BUFFERMANAGER_H
#define RAYCI_BUFFERMANAGER_H


#include <vector>
#include <mutex>

class BufferManager {
public:
    explicit BufferManager(size_t size) : buffer1(size, 0.0f), buffer2(size, 0.0f), writeBuffer(&buffer1), readBuffer(&buffer2) {}

    // 写入接口，写线程调用
    void writeData(const std::vector<float>& data) {
        std::lock_guard<std::mutex> lock(bufferSwapMutex);
        if (data.size() != writeBuffer->size()) {
            throw std::runtime_error("Data size mismatch!");
        }
        std::copy(data.begin(), data.end(), writeBuffer->begin()); // 写入到写缓冲区
        swapBuffers(); // 切换读写缓冲区
    }

    // 读取接口，读线程调用
    std::vector<float> readData() {
        std::lock_guard<std::mutex> lock(bufferSwapMutex);
        return *readBuffer; // 返回读缓冲区的副本
    }

    // 读取某个索引的值（单值读取）
    float readValue(size_t index) {
        std::lock_guard<std::mutex> lock(bufferSwapMutex);
        if (index >= readBuffer->size()) {
            throw std::out_of_range("Index out of range!");
        }
        return (*readBuffer)[index];
    }
private:
    std::vector<float> buffer1;        // 第一个缓冲区
    std::vector<float> buffer2;        // 第二个缓冲区
    std::vector<float>* writeBuffer;   // 当前写缓冲区
    std::vector<float>* readBuffer;    // 当前读缓冲区
    std::mutex bufferSwapMutex;        // 保护缓冲区切换的互斥锁

    void swapBuffers() {
        std::swap(writeBuffer, readBuffer); // 交换读写缓冲区
    }
};


#endif //RAYCI_BUFFERMANAGER_H
